//
//  ViewController.m
//  HeSiad
//
//  Created by MWJ on 15/4/23.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import <MapKit/MKAnnotation.h>
#import "ViewController.h"
#import "TourLocation.h"
#import "AnnotationView.h"
#import "AppDelegate.h"
#import "registeredViewController.h"  //注册界面
#import "leftViewController.h" //个人中心界面
#import "PostViewController.h"  //发帖子界面
#import "SetUpViewController.h" //设置界面
#import "HotPostViewController.h"    //热门帖界面
#define roundURL @"http://192.168.1.110:8888/hesaid/index.php/Hesaid/seek_home"

static NSString *const menuCellIdentifier = @"rotationCell";

@interface ViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>
@end

@implementation ViewController{
    
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    AppDelegate *app;
    NSDictionary *roundDic;
    NSMutableArray *roundArray;
    NSMutableArray *smallArray;
}

-(void)viewWillAppear:(BOOL)animated{
//    app.defaults = [NSUserDefaults standardUserDefaults];
//    app.user_id = [app.defaults objectForKey:@"yonghu"];
    app.user_id = @"63";
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self menu];
    roundArray = [NSMutableArray array];
    smallArray = [NSMutableArray array];
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    self.navigationItem.title=@"首页";

    
    //创建右边菜单按钮
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"homemenu.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightmenu)];
    self.navigationItem.rightBarButtonItem = item;
    
    //创建左边菜单
    UIBarButtonItem *leftitem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"personal.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftmenu)];
    self.navigationItem.leftBarButtonItem = leftitem;
    
    //设置导航栏颜色
    UIColor *navigationColor= [UIColor colorWithRed:180/255.0 green:180/255.0 blue:180/255.0 alpha:1];
    self.navigationController.navigationBar.barTintColor = navigationColor;
    self.navigationController.navigationBar.translucent = NO;
    
    
    self.mapview.zoomEnabled = 19;
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    //开始定位
    [locationManager startUpdatingLocation];
    [self round];
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - 左边按钮
-(void)leftmenu{
    leftViewController *leftView=[[leftViewController alloc]initWithNibName:@"leftViewController" bundle:nil];
    [self.navigationController pushViewController:leftView animated:nil];
}

-(void)menu{
    
    //第一个按钮
    UIView *postItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [postItem setMenuActionWithBlock:^{
        //点击事件
        if (app.user_id == nil||[app.user_id isEqualToString:@""]) {
            registeredViewController *reg = [self.storyboard instantiateViewControllerWithIdentifier:@"registeredVC"];
            [self.navigationController pushViewController:reg animated:YES];
        }else{
        PostViewController *post=[self.storyboard instantiateViewControllerWithIdentifier:@"postVC"];
        [self.navigationController pushViewController:post animated:YES];
        }
        
    }];
    UIImageView *postIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 35)];
    [postIcon setImage:[UIImage imageNamed:@"post"]];
    UILabel *post = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 40, 15)];
    post.text = @"发帖";
    post.textAlignment=UITextAlignmentCenter;
    post.font = [UIFont boldSystemFontOfSize:15.0f];
    [postItem addSubview:postIcon];
    [postItem addSubview:post];
    
    //第二个按钮
    UIView *hotpostItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [hotpostItem setMenuActionWithBlock:^{
        //点击事件
        HotPostViewController *hotPost=[self.storyboard instantiateViewControllerWithIdentifier:@"hotPostVC"];
        [self.navigationController pushViewController:hotPost animated:YES];
        
    }];
    UIImageView *hotpostIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 35)];
    [hotpostIcon setImage:[UIImage imageNamed:@"hotPost"]];
    UILabel *hotpost = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 40, 15)];
    hotpost.text = @"热帖";
    hotpost.textAlignment=UITextAlignmentCenter;
    hotpost.font = [UIFont boldSystemFontOfSize:15.0f];
    [hotpostItem addSubview:hotpostIcon];
    [hotpostItem addSubview:hotpost];
    
    
    self.sideMenu = [[HMSideMenu alloc] initWithItems:@[postItem, hotpostItem]];
    
    //按钮上下的间距
    [self.sideMenu setItemSpacing:10.0f];
    [self.view addSubview:self.sideMenu];
}
#pragma mark - 右边按钮菜单点击事件

-(void)rightmenu{
    if (self.sideMenu.isOpen)
        [self.sideMenu close];
    else
        [self.sideMenu open];
}
#pragma mark - 显示所有用户
-(void)round{
    NSURL *url=[NSURL URLWithString:roundURL];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *poststr =@"";
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        roundArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:roundDic waitUntilDone:YES];
        [self all];
    }];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[AnnotationView class]]) {
        static NSString* kPin = @"mn";
        AnnotationView *pinView = (AnnotationView *)
        [mapView dequeueReusableAnnotationViewWithIdentifier:kPin];
        if (!pinView) {
            pinView = [[AnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kPin];
            [pinView setDraggable:YES];
            pinView.canShowCallout=true;
            pinView.calloutOffset=CGPointMake(0, 0);
        }
        return pinView;
        
    }
    return nil;
}

-(void)refreshData{
    
}
-(void)all{
    self.locationsMutArray=[NSMutableArray array];
    for (NSDictionary *dic in roundArray) {
        AnnotationView *tourLocation=[[AnnotationView alloc]init];
        tourLocation.title=dic[@"message_content"];
        tourLocation.latitude=dic[@"message_latitude"];
        tourLocation.longitude=dic[@"message_longitude"];
        
        //把经度纬度封装
        tourLocation.coordinate=CLLocationCoordinate2DMake([dic[@"message_latitude"] doubleValue],[dic[@"message_longitude"]doubleValue]);
        [self.locationsMutArray addObject:tourLocation];
    }
    [self.mapview addAnnotations:self.locationsMutArray];
}

#pragma mark - 定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    _longitude = currentLocation.coordinate.longitude;
    _latitude = currentLocation.coordinate.latitude;
    if (currentLocation!=nil) {
        //停止获取地址位置
        [locationManager stopUpdatingLocation];
        //转换地址
        [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error==nil&&[placemarks count]>0) {
                Placemark=[placemarks lastObject];
                NSString *s1=[[NSString alloc]init];
                //地标的名字
                s1=[NSString stringWithFormat:@"%@",Placemark.name];
            }else{
                UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [Alert show];
                
            }
        }];
    }
    [self setShowMapLongitude:_longitude latitude:_latitude];
}
#pragma mark - 显示当前位置
-(void)setShowMapLongitude:(double)longitude latitude:(double)latitude{
    
    //设置经纬度
    CLLocationCoordinate2D coord={latitude,longitude};
    //设置显示范围精度
    MKCoordinateSpan span={0.5,0.5};
    //显示范围
    MKCoordinateRegion region={coord,span};
    //给地图设置显示区域
    [self.mapview setRegion:region animated:YES];
    AnnotationView *tourLocation=[[AnnotationView alloc]init];
    tourLocation.coordinate=CLLocationCoordinate2DMake(latitude,longitude);
    self.coordinate = CLLocationCoordinate2DMake(latitude,longitude);
    [self.mapview addAnnotation:tourLocation];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
